import { computed } from "vue";
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { useGlobalStore } from "@/stores/modules/global";
import { useOraStore } from "@/stores/modules/oragnization";
import { LOGIN_URL, ROUTER_WHITE_LIST } from "@/config";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter";
import I18n from "@/languages/index";

import NProgress from "@/config/nprogress";

const mode = import.meta.env.VITE_ROUTER_MODE;

const routerMode = {
  hash: () => createWebHashHistory(),
  history: () => createWebHistory()
};

/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
 * @param component ==> 视图文件路径
 * @param meta ==> 路由菜单元信息
 * @param meta.icon ==> 菜单和面包屑对应的图标
 * @param meta.title ==> 路由标题 (用作 document.title || 菜单的名称)
 * @param meta.is_Link ==> 路由外链时填写的访问地址
 * @param meta.is_Hide ==> 是否在菜单中隐藏 (通常列表详情页需要隐藏)
 * @param meta.is_full ==> 菜单是否全屏 (示例：数据大屏页面)
 * @param meta.is_affix ==> 菜单是否固定在标签页中 (首页通常是固定项)
 * @param meta.is_collect ==> 当前路由是否被收藏
 * @param meta.is_keep_alive ==> 当前路由是否缓存
 * */
const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRouter, ...errorRouter],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  // 1.NProgress 开始
  NProgress.start();
  // 2.动态设置标题
  const globalStore = useGlobalStore();
  const language = computed(() => globalStore.language); //页面翻译语种
  const title = computed(() =>
    language.value == "zh" ? import.meta.env.VITE_GLOB_APP_TITLE_CN : import.meta.env.VITE_GLOB_APP_TITLE_RU
  );
  document.title = title.value;

  //2.1加载页面翻译包 to.name
  //const toName = "login";
  //await import(/* @vite-ignore */ "https://sscn.tianxuan.work/" + toName + "_" + language.value + ".js").then(arg => {
   // I18n.global.mergeLocaleMessage(language.value!, { ...(arg.default ?? {}) });
  //});

  // 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由到登陆页
  if (to.path.toLocaleLowerCase() === LOGIN_URL) {
    if (userStore.token) return next(from.fullPath);
    resetRouter();
    return next();
  }
  // 4.判断访问页面是否在路由白名单地址(静态路由)中，如果存在直接放行
  for (let item of ROUTER_WHITE_LIST) {
    const [prefix] = item.split("/**");
    if (to.path.includes(prefix)) return next();
  }
  if (ROUTER_WHITE_LIST.includes(to.path)) return next();

  // 5.判断是否有 Token，没有重定向到 login 页面
  if (!userStore.token) return next({ path: LOGIN_URL, replace: true });

  // 6.如果没有菜单列表，就重新请求菜单列表并添加动态路由
  if (!authStore.authMenuListGet.length) {
    // console.log("==================================")
    await initDynamicRouter();

    const orgStore= useOraStore();
    await orgStore.setOrgsAll(0);//获取所有
    await orgStore.setOrgsAll(1);//获取所有
    await orgStore.setOrgsAll(2);//获取二级

    return next({ ...to, replace: true });
  }

  // 7.存储 routerName 做按钮权限筛选
  authStore.setRouteName(to.name as string);

  // 8.正常访问页面
  next();
});

/**
 * @description 重置路由
 * */
export const resetRouter = () => {
  const authStore = useAuthStore();
  authStore.flatMenuListGet.forEach(route => {
    const { name } = route;
    if (name && router.hasRoute(name)) router.removeRoute(name);
  });
};

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
  NProgress.done();
  console.warn("路由错误", error.message);
});

/**
 * @description 路由跳转结束
 * */
router.afterEach(e => {
	const authStore = useAuthStore();
	// console.log('hahahhaahaha')
	let pathIdx = authStore.addressableMenuList.findIndex(item=>item.path==e.path);
	if(pathIdx != -1){
		authStore.getAllMenuVisitNum(e.path).then(e=>{
			authStore.getCollectMenuList();
		})
	}
	NProgress.done();
});

export default router;
